package com.zcsy.seller.web.goods;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CommonImg;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.CategoryAttr;
import com.zcsy.manage.model.mall.GoodsCategory;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.GoodsSpecification;
import com.zcsy.manage.model.mall.GoodsSpecificationAttr;
import com.zcsy.manage.model.mall.vo.GoodsAttrInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.mall.GoodsInfoDao;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICommonImgService;
import com.zcsy.manage.service.mall.ICategoryAttrService;
import com.zcsy.manage.service.mall.IGoodsCategoryService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IGoodsSpecificationService;
import com.zcsy.manage.service.system.IDictService;

import net.sf.json.JSONArray;

/**
 * @Title: GoodsInfoController.java
 * @Package： com.zcsy.manage.web.mall 
 * @Description: 商品信息controller层
 *
 * @author caiyinli 13277030520@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年4月26日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value = "/goods")
public class GoodsInfoController {

	@Autowired
	private IGoodsInfoService goodsInfoService;
	
	@Autowired
	private IGoodsCategoryService goodsCategoryService;
	
	@Autowired
	private ICategoryAttrService categoryAttrService;
	
	@Autowired
	private IGoodsSpecificationService goodsSpecificationService;
	
	@Autowired
	private ICommonImgService commonImgService;
	
    private static final int GOODS_STATE  =  -1;  //商品初始状态（包括上架和下架）
    private static final int GOODS_TYPE   =  1;  //商品初始类型（ 1正常，2积分，3秒杀）
    private static final int INIT_STATE   =   1;  //新增商品初始状态（下架）
    private static final int FIRST_LEVEL  =   1;  //一级分类等级
    private static final int SORT_DEFAULT = 0;  //默认排序值
	
    @RequestMapping(value="goodsInfoList" , method = RequestMethod.GET)
    public String goodsInfoList(Model model, Integer pNo, String name, Integer state,
    		Integer goodsType,String firstLevel,String secondLevel,Integer min,Integer max,HttpServletRequest req){
    	
	    if(pNo == null){
            pNo = Constants.PAGE_NO;
        }
	    if(min == null){
	    	min = -1;
	    }
	    if(max == null){
	    	max = -1;
	    }
	    
        //此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
        PageHelper.startPage(pNo, Constants.PAGE_SIZE);
        
        GoodsInfo goodsInfo = new GoodsInfo();
        
        if(StringUtils.isNotEmpty(name)){
        	goodsInfo.setName(name);
        }
        
        if (state == null) {
			state = GOODS_STATE;
		}
        
        if (goodsType == null) {
        	goodsType = GOODS_TYPE;
        }
        
        if (goodsType != null) {
        	goodsInfo.setType(goodsType);
        }
     
        goodsInfo.setState(state);
        
        if(min != null){
        	goodsInfo.setMin(min);
        }
        
        if(max != null){
        	goodsInfo.setMax(max);
        }
        ShopInfo shopInfo = (ShopInfo)req.getSession().getAttribute(RequestConstants.SHOP_ID);
        goodsInfo.setShopId((shopInfo.getId()));
        if(secondLevel != null && secondLevel != ""){
        	goodsInfo.setGoodsCategoryId(secondLevel);
        }else if(null != firstLevel && "" != firstLevel) {
        	goodsInfo.setParentId(firstLevel);
        }
        List<GoodsInfo> goodsInfos = goodsInfoService.getGoodsByKeyword(goodsInfo);
        PageInfo<GoodsInfo> info = new PageInfo<GoodsInfo>(goodsInfos);
        
		model.addAttribute("goodsInfo", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("name", name);
		model.addAttribute("goodsType", goodsType);
		model.addAttribute("state", state);
		
		List<GoodsCategory> firstCategories = goodsCategoryService.getGoodsCategoryByLevel(FIRST_LEVEL);
		model.addAttribute("firstCategories", firstCategories);
		model.addAttribute("firstLevel", firstLevel);
		model.addAttribute("secondLevel", secondLevel);
		model.addAttribute("min", min);
		model.addAttribute("max", max);
    	return "goods/goodsInfoList";
    }
    
    @RequestMapping(value = "editGoodsInfo", method = RequestMethod.GET)
    public String editGoodsInfo(Model model, String id) {
        try {
            if (String.valueOf(Constants.STATE_DISABLED).equals(id) || null == id) {
                model.addAttribute("type", Constants.SAVE_TYPE);
            } else {
                GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
                if(goodsInfo != null){
                	model.addAttribute("type", Constants.EDIT_TYPE);
                	model.addAttribute("goodsInfo", goodsInfo);
                	GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(goodsInfo.getGoodsCategoryId());
                	model.addAttribute("goodsCategory", goodsCategory);
                	model.addAttribute("secondCategory", goodsCategoryService.getGoodsCategoryByParentId(goodsCategory.getParentId()));
                	
                	String[] key = goodsInfo.getKeyword().split("\\,");
                	String keyword = StringUtils.join(key, "|");
                	model.addAttribute("keyword", keyword);
                	
                	//根据分类id获取所有的商品分类属性
//                	List<CategoryAttr> categoryAttrs = categoryAttrService.selectByCategoryId(goodsInfo.getGoodsCategoryId());
//                	model.addAttribute("categoryAttrs", categoryAttrs);
                	
                	// 商品规格信息
                	List<GoodsSpecification> goodsSpecList = goodsSpecificationService.getGoodsSpecificationDetailByGoodsId(goodsInfo.getId());
                    model.addAttribute("goodsSpecList", goodsSpecList);
                    
                    // 商品对应规格属性值
                    List<String> attrNames = new ArrayList<>();
                    if(null != goodsSpecList && goodsSpecList.size() > 0) {
                        for(GoodsSpecificationAttr attr : goodsSpecList.get(0).getGoodsSpecificationAttrs()) {
                            attrNames.add(attr.getAttrName());
                        }
                    }
                    model.addAttribute("attrNames", attrNames);
                	
                	//获取商品banner图
                	List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_GOODS_BANNER);
                	model.addAttribute("imgs", imgs);
                }
            }
            //获取所有一级商品分类
            model.addAttribute("firstCategory", goodsCategoryService.getGoodsCategoryByLevel(1));
        
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "goods/goodsInfoEdit";
    }
    
    /**
     * @Description 通过商品分类id获取分类属性集合<br>
     * 
     * @param categoryId 商品分类id
     * @param req 用户请求
     * @return 分类属性集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年5月12日
     * @see 
     */
    @RequestMapping(value = "getGoodsAttrByCategoryId", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson getGoodsAttrByCategoryId(String categoryId,HttpServletRequest req) {
    	
    	RequestJson result = new RequestJson();
    	
    	try {
    		List<CategoryAttr> goodsCategories = categoryAttrService.selectByCategoryId(categoryId);
    		for(CategoryAttr item : goodsCategories){
    			item.setCategoryAttrValues(categoryAttrService.selectByAttrId(item.getId()));
    		}
    		result.setSuccess(true);
    		result.setObj(JSONArray.fromObject(goodsCategories).toString());
    	} catch (NumberFormatException e) {
    		result.setSuccess(false);
    		result.setMsg("操作失败");
    	}
    	return result;
    }
    
    @RequestMapping(value = "changeCategory", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson changeCategory(String id,HttpServletRequest request,HttpServletResponse response) {
        RequestJson result = new RequestJson();

        try {
        	List<GoodsCategory> categories = goodsCategoryService.getGoodsCategoryByParentId(id);
        	result.setObj(categories);
            result.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return result;
    }
    
	@RequestMapping(value="updateState" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateState( String id, int state, HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
          int flag = Constants.SQL_RESULT_ERROR;
          	  flag = goodsInfoService.updateGoodsStateByMap(id, state);
          if(flag==Constants.SQL_RESULT_SUCCESS){
        	  result.setSuccess(true);
          }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
        GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
        result.setObj(goodsInfo);
        return result;
    }
	
    @RequestMapping(value = "saveOrUpdateGoodsInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveOrUpdateGoodsInfo(@RequestBody List<GoodsAttrInfo> infoList, HttpServletRequest request,HttpServletResponse response) {
        RequestJson result = new RequestJson();
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        try {
            GoodsAttrInfo info = infoList.get(0);
        	GoodsInfo record = new GoodsInfo();
        	record.setType(Constants.GOODS_TYPE_NORMAL);
            record.setName(info.getGoodsName());
            record.setStock(Integer.parseInt(info.getStockAmount()));
            record.setGoodsCategoryId(info.getSecondCategory());
            record.setSort(SORT_DEFAULT);
            if(!StringUtil.isEmptyString(info.getPrice())){
            	record.setPrice(new BigDecimal(info.getPrice()));
            }
            if(!StringUtil.isEmptyString(info.getMarketPrice())){
                record.setMarketPrice(new BigDecimal(info.getMarketPrice()));
            }
            record.setUnit(info.getUnit());
            record.setKeyword(info.getKeyword());
            if(!StringUtil.isEmptyString(info.getIsRecommend())){
                record.setIsRecommend(Integer.parseInt(info.getIsRecommend()));
            }
            record.setDetail(info.getContainer());
//            if(!StringUtil.isEmptyString(info.getSort())){
//                record.setSort(Integer.parseInt(info.getSort()));
//            }
            
            record.setUserAccount(user.getLoginname());
            record.setLogo(info.getImageLogoUrl());
            
            if(info.getGoodsId() != ""&& !"0".equals(info.getGoodsId())){
            	record.setId(info.getGoodsId());
            	record.setUpdateTime(DateUtils.getFmtDate());
            	goodsInfoService.updateGoodsInfoAndSpec(record, infoList);
            	
            }else{
            	record.setId(UniqueNumberUtils.get18UniqueNumber());
            	record.setSendTime(DateUtils.getFmtDate());
            	record.setState(INIT_STATE);
                ShopInfo shopInfo = (ShopInfo)request.getSession().getAttribute(RequestConstants.SHOP_ID);
                record.setShopId(shopInfo.getId());
//            	record.setCategoryAttrs(categoryAttrService.selectByCategoryId(secondCategory));
//            	record.setGoodsSpecifications(goodsSpecificationService.getGoodsSpecificationByGoodsId(goodsId));
            	goodsInfoService.insert(record, infoList);
            }
            
            List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(record.getId(), Constants.IMG_GOODS_BANNER);
            
            if(CollectionUtils.isNotEmpty(imgs)){
            	for (CommonImg commonImg : imgs) {
					commonImgService.deleteById(commonImg.getId());
				}
            }
            
            CommonImg commonImg = new CommonImg();
            for (String item : info.getImgArr()) {
				commonImg.setId(UniqueNumberUtils.get18UniqueNumber());
				commonImg.setUrl(item);
				commonImg.setObjId(record.getId());
				commonImg.setObjType(Constants.IMG_GOODS_BANNER);
				commonImgService.insert(commonImg);
			}
            
            result.setObj(record);
        }catch (Exception e) {
        	e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作异常");
        }
        
        return result;
    }
    
    /**
     * @Description 根据上级分类id获取其所有下级分类集合<br>
     * 
     * @param parentId 上级分类id
     * @param req 用户请求
     * @return 当前分类的所有下级分类集合
     * @author caiyinli 13277030520@163.com
     * @date 2016年4月26日
     * @see 
     */
    @RequestMapping(value="/getCategoryByParentId", method=RequestMethod.GET)
    @ResponseBody
    public RequestJson getCategoryByParentId(String parentId, HttpServletRequest req){
    	RequestJson result = new RequestJson();
    	try {
    		List<GoodsCategory> goodsCategories = goodsCategoryService.getGoodsCategoryByParentId(parentId);
    		result.setObj(goodsCategories);
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    	return result;
    }
    
	/**
	 * @Description 实现商品置顶功能，即修改当前商品排序为所有商品中最大排序值加1，并且更新修改时间<br>
	 * 
	 * @param id 商品id
	 * @param req 用户请求
	 * @return 
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月3日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id,HttpServletRequest req){
        RequestJson result = new RequestJson();

        try {
        	if(id != null){
        		String updateTime = DateUtils.getFmtDate();
        		goodsInfoService.updateSort(id , updateTime);

        	} else {
                result.setMsg("该商品不存在！");
                result.setSuccess(false);
			}
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }

    /**
     * @description 返回商品详情
     * @param id 商品id
     * @return
     * String 商品详情路径
     * @author chenxin
     * @date 2016年9月14日下午1:26:20
     */
    @RequestMapping(value = "showDetail", method = RequestMethod.GET)
    public String showDetail(Model model, String id) {

        GoodsInfo goodsInfo = goodsInfoService.getGoodsInfoByPrimaryKey(id);
        try {
            if (goodsInfo != null) {
                
                model.addAttribute("goodsInfo", goodsInfo);
                GoodsCategory goodsCategory = goodsCategoryService.getGoodsCategoryById(goodsInfo.getGoodsCategoryId());
                model.addAttribute("goodsCategory", goodsCategory);
                model.addAttribute("secondCategory",
                        goodsCategoryService.getGoodsCategoryByParentId(goodsCategory.getParentId()));

                String[] key = goodsInfo.getKeyword().split("\\,");
                String keyword = StringUtils.join(key, "|");
                model.addAttribute("keyword", keyword);
                
                // 商品规格信息
                List<GoodsSpecification> goodsSpecList = goodsSpecificationService
                        .getGoodsSpecificationDetailByGoodsId(goodsInfo.getId());
                model.addAttribute("goodsSpecList", goodsSpecList);

                // 商品对应规格属性值
                List<String> attrNames = new ArrayList<>();
                if (null != goodsSpecList && goodsSpecList.size() > 0) {
                    for (GoodsSpecificationAttr attr : goodsSpecList.get(0).getGoodsSpecificationAttrs()) {
                        attrNames.add(attr.getAttrName());
                    }
                }
                model.addAttribute("attrNames", attrNames);

                // 获取商品banner图
                List<CommonImg> imgs = commonImgService.selectImgsByObjIdAndObjType(id, Constants.IMG_GOODS_BANNER);
                model.addAttribute("imgs", imgs);

            }
            // 获取所有一级商品分类
            model.addAttribute("firstCategory", goodsCategoryService.getGoodsCategoryByLevel(Constants.STATE_ENABLED));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "goods/goodsInfoDetail";
    }

}